package liuch.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import liuch.netty.session.NettySession;
import liuch.netty.session.NettySessionRepository;

/**
 * @author: liuchenhui
 * @create: 2019-01-16 11:26
 **/
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat",
            CharsetUtil.UTF_8));

    // 处理消息
    private void handleMessage(String message) {
        System.out.println("msg = " + message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = msg.toString();
        System.out.println("Server received: " + message);
        if (message.contains("sn")) {
            String sn = message.split(",")[0];
            // 添加session
            NettySession nettySession = new NettySession();
            nettySession.setId(sn);
            nettySession.setSession(ctx);
            NettySessionRepository.addSession(nettySession);
        }
        // 设置考勤机状态

        // 处理message
        handleMessage(message);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端读取消息完成");
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        NettySessionRepository.close(ctx);
        System.out.println("处理消息异常" + cause.getMessage());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//        LOGGER.debug("客户端关闭连接");
        NettySessionRepository.close(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("新客户端连接");
        // TODO: 2019-01-17 初始化
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        // 发现客户端失联断开链路
        if (evt instanceof IdleStateEvent) {
            ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
